<template>
  <view class="user-info-main apply-order">
    <!-- 头像  -->
    <view class="avatar-main">
      <uni-file-picker
        v-model="imageAvarValue"
        limit="1"
        :del-icon="false"
        disable-preview
        :imageStyles="imageStyles"
        fileMediatype="image"
        @select="handleSelectImage"
        @progress="progressImage"
        @success="successImage"
        @fail="failImage"
        />
      <!-- <image class="avatar-img" :src="orderForm.avarImage" mode="aspectFill"></image> -->
    </view>
    <!-- 表单 -->
    <view class="user-card">
      <uni-card shadow="0px 0px 3px 1px rgba(0, 0, 0, 0.08)" >
        <uni-forms ref="userFormRef" :modelValue="orderForm" :rules="userFormRules" :border="true" class="card-form">
          <uni-forms-item label="名字" name="username" required>
            <uni-easyinput  v-model="orderForm.username" placeholder="请输入" />
          </uni-forms-item>
          <uni-forms-item label="账号" name="user_code" required>
            <uni-easyinput  v-model="orderForm.userCode" placeholder="请输入" />
          </uni-forms-item>
          <uni-forms-item label="简介" name="introduce">
            <uni-easyinput type="textarea" v-model="orderForm.introduce" placeholder="请输入" />
          </uni-forms-item>
					<uni-forms-item label="性别">
						<uni-data-checkbox v-model="orderForm.sex" :localdata="sexsData" />
					</uni-forms-item>
					<uni-forms-item label="生日">
						<uni-datetime-picker 
              type="date" 
              return-type="timestamp" 
              v-model="orderForm.birdTime"
            />
					</uni-forms-item>
          <uni-forms-item label="地区">
          	<picker mode="region" :value="orderForm.fullLocation.split(' ')" @change="handleRegionChange">
              <view v-if="orderForm.fullLocation">{{orderForm.fullLocation}}</view>
              <view v-else class="uni-input"> 请选择省/市/区(县) </view>
            </picker>
          </uni-forms-item>
         <uni-forms-item label="背景图">
          	<uni-file-picker 
              v-model="imageBgValue"
              limit="1"
              :del-icon="false"
              disable-preview
              :imageStyles="imageTwoStyles"
              fileMediatype="image"
              @select="handleSelectImageTwo"
              />
          </uni-forms-item>
        </uni-forms>
      </uni-card>
    </view>
    <!-- 底部-按钮 -->
    <view class="btn-group">
      <button class="red-btn" @click="handleSave">保存</button>
    </view>
  </view>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
import { formatDate } from '../../utils/formatDate';

  /** 表单 **/ 
  const orderForm = ref({
    fullLocation: '', // 省市区(前端展示)
    provinceCode: '', // 省份编码(后端参数)
    cityCode: '', // 城市编码(后端参数)
    countyCode: '', // 区/县编码(后端参数)
    provinceName: '', // 省份编码(后端参数)
    cityName: '', // 城市编码(后端参数)
    countyName: '', // 区/县编码(后端参数)
    avarImage: null,
    bgImage: null,
  })
  const fullLocation = ref('')
  const userFormRef = ref(null)
  const userFormRules = ref({
    username: {
      rules: [ { required: true, errorMessage: '必填' } ],
    },
    userNum:{ 
      rules:  [ { required: true, errorMessage: '必填' } ]
    }
  })
  const sexsData = ref([ { text: '男',value: 0 },{ text: '女',value: 1 } ])
  
  /** 获取地区 **/ 
  const handleRegionChange = (e)=> {
    // 前端展示（省市区）
   orderForm.value.fullLocation = e.detail.value.join(' ')
   
    // 后端保存参数
    const [provinceCode,cityCode,countyCode] = e.detail.code
    const [provinceName,cityName,countyName] = e.detail.value
    Object.assign(orderForm.value,{ provinceCode,cityCode,countyCode })
    Object.assign(orderForm.value,{ provinceName,cityName,countyName })
  }
  
  /**本地缓存获取登录用户信息**/ 
  const usersInfo = uni.getStorageSync('userInfo')
  
  /** 获取用户信息接口 **/ 
  const getUserData = async ()=>{
    const { data: res } = await uni.$http.get('/getUserInfo',{ id: usersInfo.id })
    if(res.success) {
      orderForm.value = res.data
      imageAvarValue.value = JSON.parse(res.data.avarImage) 
      imageBgValue.value = JSON.parse(res.data.bgImage)
    } else {
      uni.showToast({  title: res.msg, duration: 3000, icon:'none' })
    }
  }
  
  /** 提交保存**/
  const handleSave =async ()=>{
    const dateTime = formatDate(orderForm.value.birdTime,'yyyy-MM-dd hh:mm:ss')
    orderForm.value.birdTime = dateTime 
    const { data: res } = await uni.$http.post('/updateUserInfo',orderForm.value)
    if (res.success) {
      getUserData()  // 刷新信息
    } 
    uni.showToast({ title: res.msg, duration: 3000, icon:'none' }) 
  }
  
  /** 头像 **/
  const imageStyles = ref({ 
    width: 90, 
    height: 90, 
    border: { radius: ' 50%',"color":"#efefef","width":"1px","style":"solid" } 
  })
  const imageAvarValue = ref({})
  // 上传图片
  const handleSelectImage = (e)=>{
    orderForm.value.avarImage = JSON.stringify(e.tempFiles) 
  } 
  const progressImage = (e)=>{
    console.log('上传进度：',e)
  }
  const successImage = (e)=>{
    console.log('上传成功')
  }
  const failImage = (e)=>{
    uni.showToast({  title: '上传失败！', duration: 3000, icon:'none' })
    console.log('上传失败：',e)
  }
  
  /** 上传背景图 **/ 
  const imageBgValue = ref([])
  const imageTwoStyles = ref({ width: 200, height: 90, border: { "color":"#efefef","width":"1px","style":"solid" } })
  const handleSelectImageTwo = (e)=>{
    orderForm.value.bgImage = JSON.stringify(e.tempFiles)
  }
  
onMounted(()=>{
  getUserData()
})
</script>

<style lang="scss">
.user-info-main {
  .avatar-main {
    margin-top: 20px;
  }
  .user-card{
    width: 100%;
    .card-form {
        padding: 10px !important;
    }
  }
}

</style>
